package com.ruoyi.web.core.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.system.domain.SysUser;
import io.jsonwebtoken.ExpiredJwtException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author tang ao long
 * @Date 2020-09-02 15:45
 * @Version 1.0
 */
public class JwtUtil {

    public static String getToken(SysUser user) {
        String token="";
        token= JWT.create().withAudience(user.getUserId().toString())
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }

    //过期时间 30分钟
    private static final long EXPIRE_TIME = 30 * 60 * 1000;
    //私钥
    private static final String TOKEN_SECRET = "2168a0c2-7205-4162-a3c6-d50305374792";//私钥uuid

    /**
     * 生成签名
     * @param **username**
     * @param **password**
     * @return
     */
    public static String sign(Long userId) {
        try {
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim("userId", userId)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检验token是否正确
     * @param **token**
     * @return
     */
    public static Long verify(String token){
            try {
                Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
                JWTVerifier verifier = JWT.require(algorithm).build();
                DecodedJWT jwt = verifier.verify(token);
                Long userId = jwt.getClaim("userId").asLong();
                return userId;
            }catch (ExpiredJwtException e){
                throw new BusinessException("检测token错误");
            }
    }

}
